import 'package:chewie/chewie.dart';
import 'package:effective/service/api.dart';
import 'package:effective/utils/base_view.dart';
import 'package:effective/view_model/annotation_viewmodel.dart';
import 'package:effective/view_model/user_model.dart';
import 'package:effective/widget/common_dialog.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class Annotation extends StatefulWidget {
  Annotation({Key key}) : super(key: key);

  @override
  _AnnotationState createState() => _AnnotationState();
}

class _AnnotationState extends State<Annotation> {
  TextStyle textStyle = TextStyle(
    fontWeight: FontWeight.w600,
    fontSize: 20,
  );

  @override
  Widget build(BuildContext context) {
    return BaseView<AnnotationViewModel>(
      model: AnnotationViewModel(api: API()),
      onModelReady: (model) async {
        await model.loadData(context);
      },
      builder: (context, model, child) {
        return Scaffold(
          appBar: PreferredSize(
            child: AppBar(
              elevation: 0,
              foregroundColor: Colors.white,
              backgroundColor: Colors.white,
              title: Container(
                margin: EdgeInsets.fromLTRB(87, 25, 0, 16),
                child: Row(
                  mainAxisSize: MainAxisSize.max,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Container(
                      child: Text.rich(TextSpan(children: [
                        TextSpan(
                            text: 'E',
                            style: TextStyle(fontSize: 28, color: Colors.blue)),
                        TextSpan(
                            text: '-ffective',
                            style:
                                TextStyle(fontSize: 25, color: Colors.black)),
                      ])),
                    ),
                    Expanded(
                      child: Container(),
                      flex: 1,
                    ),
                    Container(
                      margin: EdgeInsets.fromLTRB(0, 0, 25, 0),
                      child: Row(
                        children: [
                          Container(
                            margin: EdgeInsets.only(right: 20),
                            child: Provider.of<UserModel>(context).value == ""
                                ? Text(
                                    '请登录后操作',
                                    style: TextStyle(
                                        fontSize: 20, color: Colors.black),
                                  )
                                : Text.rich(TextSpan(children: [
                                    TextSpan(
                                      text: 'Hello, ',
                                      style: TextStyle(
                                          fontSize: 20, color: Colors.black),
                                    ),
                                    TextSpan(
                                      text:
                                          Provider.of<UserModel>(context).value,
                                      style: TextStyle(
                                          fontSize: 20, color: Colors.blue),
                                    ),
                                  ])),
                          ),
                          Provider.of<UserModel>(context).value == ""
                              ? Container(
                                  height: 35,
                                  width: 105,
                                  child: OutlineButton(
                                    borderSide: BorderSide(
                                        width: 2, color: Colors.blue),
                                    textColor: Colors.blue,
                                    color: Colors.white,
                                    shape: RoundedRectangleBorder(
                                        side: BorderSide.none,
                                        borderRadius: BorderRadius.all(
                                            Radius.circular(50))),
                                    onPressed: () async {
                                      model.login(context);
                                    },
                                    child: Text(
                                      'LOG IN',
                                      style: TextStyle(fontSize: 16),
                                    ),
                                  ),
                                )
                              : Container(
                                  height: 35,
                                  width: 105,
                                  child: OutlineButton(
                                    borderSide: BorderSide(
                                        width: 2, color: Colors.blue),
                                    textColor: Colors.blue,
                                    color: Colors.white,
                                    shape: RoundedRectangleBorder(
                                        side: BorderSide.none,
                                        borderRadius: BorderRadius.all(
                                            Radius.circular(50))),
                                    onPressed: () async {
                                      model.logout(context);
                                    },
                                    child: Text(
                                      'LOG OUT',
                                      style: TextStyle(fontSize: 16),
                                    ),
                                  ),
                                ),
                        ],
                      ),
                    )
                  ],
                ),
              ),
              automaticallyImplyLeading: false,
            ),
            preferredSize: Size(MediaQuery.of(context).size.width, 70),
          ),
          body: Container(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Container(
                  color: Colors.grey[500],
                  height: 2,
                  width: MediaQuery.of(context).size.width,
                ),
                Expanded(
                  child: SingleChildScrollView(child: mainPage(model)),
                  flex: 1,
                ),
                Container(
                  width: MediaQuery.of(context).size.width,
                  height: 79,
                  child: Image.asset('assets/bottom.png',fit: BoxFit.fill,),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget mainPage(AnnotationViewModel model) {
    return Container(
      margin: EdgeInsets.fromLTRB(94, 0, 94, 0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Container(
            margin: EdgeInsets.only(top: 20),
            child: Text(
              'ANNOTATE YOUR SPEECH VIDEO',
              style: TextStyle(fontSize: 30, fontWeight: FontWeight.w500),
            ),
          ),
          notice(model),
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Container(
                margin: EdgeInsets.fromLTRB(0, 20, 0, 20),
                child: Text.rich(TextSpan(children: [
                  TextSpan(
                      text: 'Description',
                      style:
                          TextStyle(fontWeight: FontWeight.w600, fontSize: 20)),
                  TextSpan(
                      text: '(50-100 words) [options]',
                      style: TextStyle(fontSize: 20)),
                ])),
              )
            ],
          ),
          input(model.description),
          Container(
            margin: EdgeInsets.only(top: 20),
            child: highlights(model),
          ),
          Container(
            margin: EdgeInsets.fromLTRB(40, 40, 40, 20),
            child: Wrap(
              alignment: WrapAlignment.center,
              children: [
                Container(
                  child: Checkbox(
                    value: model.agreeVolunteer,
                    onChanged: (value) => model.changeVolunteer(value),
                  ),
                ),
                Container(
                  child: Text(
                      'I volunteer to upload my speech data and agree the research team to ues my data under the IRB. Also I am willing to receive the e-mails from the research team',
                      style: TextStyle(fontSize: 20)),
                )
              ],
            ),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              MaterialButton(
                height: 49,
                minWidth: 105,
                elevation: 0,
                textColor: Colors.white,
                color: Color(0xFF7484F4),
                shape: RoundedRectangleBorder(
                    side: BorderSide.none,
                    borderRadius: BorderRadius.all(Radius.circular(50))),
                onPressed: () => model.submit(context),
                child: Text(
                  'SUBMIT',
                  style: TextStyle(fontSize: 16),
                ),
              ),
              Container(
                height: 40,
                width: 100,
                child: OutlineButton(
                  borderSide: BorderSide(width: 2, color: Colors.blue),
                  textColor: Colors.blue,
                  color: Colors.white,
                  shape: RoundedRectangleBorder(
                      side: BorderSide.none,
                      borderRadius: BorderRadius.all(Radius.circular(50))),
                  onPressed: () => model.reset(),
                  child: Text(
                    'RESET',
                    style: TextStyle(fontSize: 16),
                  ),
                ),
              )
            ],
          ),
        ],
      ),
    );
  }

  Widget notice(AnnotationViewModel model) {
    return Container(
      width: MediaQuery.of(context).size.width,
      margin: EdgeInsets.fromLTRB(0, 20, 0, 0),
      padding: EdgeInsets.fromLTRB(19, 30, 19, 15),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.grey[500], width: 1),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            child: Text.rich(TextSpan(children: [
              TextSpan(
                  text: 'Notice: ',
                  style: TextStyle(fontWeight: FontWeight.w600, fontSize: 20)),
              TextSpan(
                  text:
                      'The annotated data will be used for academic research and non-profit usage. Your data and personal information will never be leaked to anyone without your permission. By contributing your data, more researches based on big data can be carried on. The results of the researches will provide more service to you in return. We much appreciate your kind contribution!',
                  style: TextStyle(fontSize: 20))
            ])),
          ),
          Container(
            margin: EdgeInsets.only(top: 20),
            child: Wrap(
              alignment: WrapAlignment.center,
              children: [
                Container(
                  child: Text.rich(TextSpan(children: [
                    TextSpan(
                        text:
                            'Please read the IRB before you upload any data  ',
                        style: TextStyle(
                            fontSize: 20, fontWeight: FontWeight.w600)),
                    TextSpan(
                        text: '(click here)',
                        style: TextStyle(
                            fontSize: 20,
                            fontWeight: FontWeight.w600,
                            decoration: TextDecoration.underline),
                        recognizer: TapGestureRecognizer()
                          ..onTap = () async {
                            //open
                            bool result =
                                await CommonDialog.annotationConfirmDialog(
                                    context);
                            model.changeNoticeState(result);
                            //TODO 待定
                          }),
                  ])),
                ),
                Container(
                  child: Row(
                    children: [
                      Checkbox(
                        value: model.agreeNotice,
                        onChanged: (value) => model.changeNoticeState(value),
                      ),
                      Container(
                        child: Text(
                          'I understand the IRB and agree to it.',
                          style: TextStyle(
                            fontWeight: FontWeight.w600,
                            fontSize: 20,
                          ),
                        ),
                      )
                    ],
                  ),
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget highlights(AnnotationViewModel model) {
    return Container(
      height: 300,
      child: Row(
        children: [
          Expanded(
            child: Container(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    child: Text.rich(TextSpan(children: [
                      TextSpan(text: 'Highlights', style: textStyle),
                      TextSpan(
                          text: '[optional]', style: TextStyle(fontSize: 20)),
                    ])),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 10),
                    child: Text(
                      'Highlights are the segments of speech videos that are interesting and attracting to the audience because of the expressive performance of the speaker. The highlights may contain the segments that you express the contents well by facial expressions, body gestures, vocal expressions and so on.',
                      style: TextStyle(fontSize: 20),
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 10),
                    child: Text(
                      'Please play the video and press the button “Highlight Start”/“Highlight End” at the start/end of each highlight segment.',
                      style: TextStyle(fontSize: 20),
                    ),
                  )
                ],
              ),
            ),
            flex: 1,
          ),
          Expanded(
            child: Container(
              child: Row(
                children: [
                  Expanded(
                    child: Container(
                      decoration: BoxDecoration(
                        border: Border.all(width: 1, color: Colors.grey),
                      ),
                      child: model.chewieController != null &&
                              model.chewieController.videoPlayerController.value
                                  .isInitialized
                          ? Chewie(controller: model.chewieController)
                          : Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: const [
                                CircularProgressIndicator(),
                                SizedBox(height: 20),
                                Text('Loading'),
                              ],
                            ),
                    ),
                    flex: 3,
                  ),
                  Expanded(
                    child: Container(
                      margin: EdgeInsets.only(left: 5),
                      child: Column(
                        children: [
                          Expanded(
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Expanded(
                                  child: Center(
                                    child: Text(
                                      'ID',
                                      style: TextStyle(
                                          fontWeight: FontWeight.w600),
                                    ),
                                  ),
                                  flex: 3,
                                ),
                                Expanded(
                                  child: Center(
                                    child: Text('Start',
                                        style: TextStyle(
                                            fontWeight: FontWeight.w600)),
                                  ),
                                  flex: 3,
                                ),
                                Expanded(
                                  child: Center(
                                    child: Text('END',
                                        style: TextStyle(
                                            fontWeight: FontWeight.w600)),
                                  ),
                                  flex: 3,
                                ),
                                Expanded(
                                  child: Container(),
                                  flex: 1,
                                ),
                              ],
                            ),
                            flex: 2,
                          ),
                          Expanded(
                            child: Container(
                              child: ListView.builder(
                                itemBuilder: (context, pos) {
                                  return Container(
                                    margin: EdgeInsets.fromLTRB(0, 2, 0, 2),
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Expanded(
                                          child: Center(
                                            child: Text(pos.toString()),
                                          ),
                                          flex: 3,
                                        ),
                                        Expanded(
                                          child: Center(
                                            child: Text(
                                                model.highlights[pos].start),
                                          ),
                                          flex: 3,
                                        ),
                                        Expanded(
                                          child: Center(
                                            child:
                                                Text(model.highlights[pos].end),
                                          ),
                                          flex: 3,
                                        ),
                                        Expanded(
                                          child: Center(
                                            child: GestureDetector(
                                              child: Icon(
                                                Icons.close,
                                                size: 12,
                                              ),
                                              onTap: () {
                                                model.deleteHighlight(pos);
                                              },
                                            ),
                                          ),
                                          flex: 1,
                                        ),
                                      ],
                                    ),
                                  );
                                },
                                itemCount: model.highlights.length,
                              ),
                            ),
                            flex: 16,
                          ),
                          Expanded(
                            child: Container(
                              margin: EdgeInsets.only(top: 10),
                              child: Center(
                                child: Container(
                                  child: MaterialButton(
                                    height: 49,
                                    minWidth: 105,
                                    elevation: 0,
                                    textColor: Colors.white,
                                    color: model.startOrEnd
                                        ? Colors.red
                                        : Color(0xFF7484F4),
                                    shape: RoundedRectangleBorder(
                                        side: BorderSide.none,
                                        borderRadius: BorderRadius.all(
                                            Radius.circular(50))),
                                    onPressed: () {
                                      if (model.startOrEnd) {
                                        model.hightlightEnd(model
                                            .chewieController
                                            .videoPlayerController
                                            .value
                                            .position
                                            .inMilliseconds);
                                      } else {
                                        model.hightlightStart(model
                                            .chewieController
                                            .videoPlayerController
                                            .value
                                            .position
                                            .inMilliseconds);
                                      }
                                    },
                                    child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      children: [
                                        Text(
                                          'Highlight',
                                          style: TextStyle(fontSize: 16),
                                        ),
                                        Text(
                                          model.startOrEnd ? 'End' : 'Start',
                                          style: TextStyle(fontSize: 16),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ),
                            ),
                            flex: 5,
                          ),
                        ],
                      ),
                    ),
                    flex: 2,
                  ),
                ],
              ),
            ),
            flex: 1,
          ),
        ],
      ),
    );
  }

  Widget input(TextEditingController textEditingController) {
    return Container(
      width: MediaQuery.of(context).size.width,
      height: 80,
      decoration:
          BoxDecoration(border: Border.all(color: Colors.black, width: 2)),
      child: TextField(
        controller: textEditingController,
        maxLength: 100,
        maxLines: 3,
        decoration: InputDecoration(
            border: InputBorder.none,
            contentPadding: EdgeInsets.fromLTRB(2, 8, 0, 0)),
        style: TextStyle(fontSize: 18),
        cursorHeight: 24,
      ),
    );
  }
}
